<template>
  <div class="orders">
    <div class="header">
      <h1>我的订单</h1>
    </div>
    
    <div class="order-filter">
      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <el-tab-pane label="全部订单" name="all"></el-tab-pane>
        <el-tab-pane label="待付款" name="0"></el-tab-pane>
        <el-tab-pane label="待发货" name="1"></el-tab-pane>
        <el-tab-pane label="已发货" name="2"></el-tab-pane>
        <el-tab-pane label="已完成" name="3"></el-tab-pane>
        <el-tab-pane label="已取消" name="4"></el-tab-pane>
        <el-tab-pane label="退款中" name="5"></el-tab-pane>
      </el-tabs>
    </div>
    
    <div class="order-list" v-loading="loading">
      <!-- 无订单提示 -->
      <div v-if="!loading && orderList.length === 0" class="no-orders">
        <el-empty description="目前您还没有订单">
          <el-button type="primary" @click="goShopping">去购物</el-button>
        </el-empty>
      </div>
      
      <!-- 订单列表 -->
      <div v-else>
        <el-card 
          v-for="order in orderList" 
          :key="order.id" 
          class="order-card"
        >
          <div class="order-header">
            <div class="order-info">
              <span class="order-no">订单编号：{{ order.orderNo }}</span>
              <span class="order-time">创建时间：{{ formatDate(order.createdAt) }}</span>
            </div>
            <div class="order-status">
              {{ getOrderStatusText(order.status) }}
            </div>
          </div>
          
          <div class="order-items" v-if="order.items && order.items.length > 0">
            <div 
              v-for="item in order.items" 
              :key="item.id" 
              class="order-item"
              @click="goToProductDetail(item.productId)"
            >
              <img :src="item.productImage" alt="商品图片" class="item-image">
              <div class="item-info">
                <div class="item-name">{{ item.productName }}</div>
                <div class="item-price">¥{{ item.productPrice.toFixed(2) }}</div>
                <div class="item-quantity">x{{ item.quantity }}</div>
              </div>
            </div>
          </div>
          
          <div class="order-footer">
            <div class="order-total">
              共{{ order.items ? order.items.length : 0 }}件商品 合计：¥{{ order.totalAmount.toFixed(2) }}
            </div>
            <div class="order-actions">
              <template v-if="order.status === 0">
                <el-button @click="handlePay(order.id)">去支付</el-button>
                <el-button type="danger" @click="handleCancel(order.id)">取消订单</el-button>
              </template>
              <template v-else-if="order.status === 1">
                <el-button>联系客服</el-button>
              </template>
              <template v-else-if="order.status === 2">
                <el-button type="primary" @click="handleConfirm(order.id)">确认收货</el-button>
              </template>
              <template v-else-if="order.status === 3">
                <el-button type="primary">评价商品</el-button>
              </template>
              <template v-else-if="order.status === 4">
                <el-button type="danger" @click="handleDelete(order.id)">删除订单</el-button>
              </template>
              <template v-else-if="order.status === 5">
                <el-button>联系客服</el-button>
              </template>
              <el-button type="text" @click="goToOrderDetail(order.id)">查看详情</el-button>
            </div>
          </div>
        </el-card>
      </div>
    </div>
    
    <!-- 分页 -->
    <div v-if="orderList.length > 0" class="pagination">
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { orderService } from '../services/orderService'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '../store'
import dayjs from 'dayjs'

const router = useRouter()
const userStore = useUserStore()

// 订单列表数据
const orderList = ref([])

// 当前选中的标签页（订单状态）
const activeTab = ref('all')

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)

// 处理401错误
const handleUnauthorizedError = () => {
  ElMessageBox.confirm(
    '您的登录已过期，请重新登录',
    '登录已过期',
    {
      confirmButtonText: '去登录',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    router.push('/login')
  }).catch(() => {
    // 用户取消操作，不做任何处理
  })
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  return dayjs(dateString).format('YYYY-MM-DD HH:mm:ss')
}

// 获取订单状态文本
const getOrderStatusText = (status) => {
  const statusMap = {
    0: '待付款',
    1: '待发货',
    2: '已发货',
    3: '已完成',
    4: '已取消',
    5: '退款中',
    6: '已退款'
  }
  return statusMap[status] || '未知状态'
}

// 加载订单列表
const loadOrders = async () => {
  loading.value = true
  try {
    console.log('开始加载订单列表，当前标签页:', activeTab.value)
    console.log('用户认证状态:', userStore.isAuthenticated)
    console.log('用户ID:', userStore.userInfo?.id || userStore.userInfo?.userId)
    
    if (!userStore.isAuthenticated) {
      orderList.value = []
      total.value = 0
      loading.value = false
      return
    }
    
    let result
    if (activeTab.value === 'all') {
      // 获取所有订单
      console.log('获取所有订单，页码:', currentPage.value, '每页大小:', pageSize.value)
      result = await orderService.getUserOrders(currentPage.value, pageSize.value)
    } else {
      // 根据状态获取订单
      console.log('根据状态获取订单，状态:', activeTab.value, '页码:', currentPage.value, '每页大小:', pageSize.value)
      result = await orderService.getUserOrdersByStatus(activeTab.value, currentPage.value, pageSize.value)
    }
    
    console.log('订单列表数据:', result)
    orderList.value = result.orders || []
    total.value = result.total || 0
    console.log('处理后的订单列表:', orderList.value, '总数:', total.value)
  } catch (error) {
    console.error('加载订单列表失败:', error)
    
    // 根据错误类型提供更友好的错误提示
    if (error.statusCode === 401) {
      // 如果是401错误，清空订单列表并显示无订单提示
      orderList.value = []
      total.value = 0
    } else if (error.response) {
      // 服务器返回的错误
      switch (error.response.status) {
        case 403:
          ElMessage.error('无权限访问订单信息')
          break
        case 404:
          ElMessage.error('订单服务暂时不可用')
          break
        case 500:
          ElMessage.error('服务器错误，请稍后再试')
          break
        default:
          ElMessage.error(`加载订单失败: ${error.response.data.message || '未知错误'}`)
      }
    } else if (error.request) {
      // 请求已发出但没有收到响应
      ElMessage.error('网络错误，请检查网络连接')
    } else {
      // 请求设置出错
      ElMessage.error(`加载订单失败: ${error.message}`)
    }
  } finally {
    loading.value = false
  }
}

// 去购物
const goShopping = () => {
  router.push('/')
}

// 标签页切换
const handleTabChange = () => {
  currentPage.value = 1
  loadOrders()
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  loadOrders()
}

// 当前页改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  loadOrders()
}

// 跳转到商品详情
const goToProductDetail = (productId) => {
  router.push(`/products/${productId}`)
}

// 跳转到订单详情
const goToOrderDetail = (orderId) => {
  router.push(`/orders/${orderId}`)
}

// 支付订单
const handlePay = async (orderId) => {
  try {
    await orderService.payOrder(orderId)
    ElMessage.success('支付成功')
    loadOrders()
  } catch (error) {
    console.error('支付失败:', error)
    
    // 处理401错误
    if (error.statusCode === 401) {
      handleUnauthorizedError()
    } else {
      ElMessage.error('支付失败，请重试')
    }
  }
}

// 取消订单
const handleCancel = async (orderId) => {
  try {
    await orderService.cancelOrder(orderId)
    ElMessage.success('订单已取消')
    loadOrders()
  } catch (error) {
    console.error('取消订单失败:', error)
    
    // 处理401错误
    if (error.statusCode === 401) {
      handleUnauthorizedError()
    } else {
      ElMessage.error('取消订单失败，请重试')
    }
  }
}

// 确认收货
const handleConfirm = async (orderId) => {
  try {
    await orderService.confirmOrder(orderId)
    ElMessage.success('已确认收货')
    loadOrders()
  } catch (error) {
    console.error('确认收货失败:', error)
    
    // 处理401错误
    if (error.statusCode === 401) {
      handleUnauthorizedError()
    } else {
      ElMessage.error('确认收货失败，请重试')
    }
  }
}

// 删除订单
const handleDelete = async (orderId) => {
  try {
    await ElMessageBox.confirm('确定要删除该订单吗？删除后将无法恢复', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await orderService.deleteOrder(orderId)
    ElMessage.success('订单已删除')
    loadOrders()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除订单失败:', error)
      
      // 处理401错误
      if (error.statusCode === 401) {
        handleUnauthorizedError()
      } else {
        ElMessage.error('删除订单失败，请重试')
      }
    }
  }
}

// 页面加载时初始化数据
onMounted(() => {
  loadOrders()
})
</script>

<style scoped>
.orders {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.order-filter {
  margin-bottom: 20px;
}

.order-list {
  margin-bottom: 20px;
}

.order-card {
  margin-bottom: 20px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.order-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.order-no {
  font-weight: bold;
}

.order-time {
  color: #999;
  font-size: 14px;
}

.order-status {
  color: #409EFF;
  font-weight: bold;
}

.order-items {
  margin-bottom: 15px;
}

.order-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  cursor: pointer;
}

.item-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  margin-right: 10px;
  border-radius: 4px;
}

.item-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.item-name {
  font-weight: bold;
}

.item-price {
  color: #E6A23C;
}

.item-quantity {
  color: #999;
  font-size: 14px;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 10px;
  border-top: 1px solid #eee;
}

.order-total {
  font-weight: bold;
}

.order-actions {
  display: flex;
  gap: 10px;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.no-orders {
  padding: 40px 0;
  text-align: center;
}
</style>